package com.zhanglu.fun.services.chatroom.message;

import com.zhanglu.fun.services.chatroom.bean.request.MessageRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description
 * @Auther zhanglu
 * @Date 2017/10/19 上午9:43
 */
@RestController
@Slf4j
public class TestMessage {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/send/all")
    @SendTo("/topic/send/all")
    public MessageRequest sendToAll(MessageRequest messageRequest) {
        messageRequest.setMessageDate(new Date());
        log.debug("sendToAll receive params are:[param json : {}]", messageRequest.toString());
        return messageRequest;
    }

    @MessageMapping("/send/group")
    public void sendToGroup(MessageRequest messageRequest) {// 暂时组名称是传过来的，后期优化加入密钥，所有信息不可见。需要加密解密。
        messageRequest.setMessageDate(new Date());
        log.debug("sendToGroup receive params are:[param json : {}]", messageRequest.toString());
        String sendPath = "/topic/send/group/" + messageRequest.getGroupName();
        messagingTemplate.convertAndSend(sendPath, messageRequest);
    }

    @MessageMapping("/send/user")
    // @SendToUser("/topic/send/user")
    public void sendToUser(MessageRequest messageRequest) {
        messageRequest.setMessageDate(new Date());
        log.debug("sendToUser receive params are:[param json : {}]", messageRequest.toString());
        messagingTemplate.convertAndSendToUser(messageRequest.getFunNo(), "/topic/send/user", messageRequest);
    }

    @Scheduled(fixedRate = 1000)
    @SendTo("/topic/callback")
    public void getServerTime() {
        messagingTemplate.convertAndSend("/topic/callback", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}
